package com.session;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * Created by lzx on 16/7/8.
 * 服务器端限制表单重复提交
 */
@Controller
public class SessionSampleController {

    @RequestMapping(value = "/session",method = RequestMethod.GET)
    public String index(HttpServletRequest request){
        HttpSession session = request.getSession(true);
        session.setAttribute("token", UUID.randomUUID().toString());
        System.out.println("index--"+session.getAttribute("token"));
        return "session/sessionsample";
    }

    @RequestMapping(value = "/form",method = RequestMethod.POST)
    @ResponseBody
    public Object formSubmit(HttpServletRequest request,String username,String token) throws InterruptedException {
        System.out.println(username);
        Thread.sleep(3000);
        HttpSession session = request.getSession(false);
        System.out.println("client--"+token);
        System.out.println("server--"+session.getAttribute("token"));
        if(session==null){
            return ResponseEntity.badRequest().body("重复提交");
        }else {
            Object sessionAttribute = session.getAttribute("token");
            if (sessionAttribute == null || !StringUtils.equals(sessionAttribute.toString(), token)) {
                return ResponseEntity.badRequest().body("重复提交");
            }else{
                session.removeAttribute("token");
                return ResponseEntity.ok().build();
            }
        }
    }

    @RequestMapping(value = "/session/sessionA")
    public String sessionA(HttpServletRequest request){
        System.err.println("forward  "+request.getSession(false).getId());
        return "session/sessionA";
    }
    @RequestMapping(value = "/testRedirect/sessionB")
    public String testRedirect(){
        return "redirect:/session/sessionB";
    }

    @RequestMapping(value = "/session/sessionB")
    public String sessionB(HttpServletRequest request) {
        System.err.println("redirect  " + request.getSession(false).getId());
        return "session/sessionB";
    }

}
